package com.lcy.redismessage.listener;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lcy.redismessage.service.MessageService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import java.util.concurrent.CountDownLatch;

@Configuration
public class RedisMessageListener {

    @Value("${channelname}")
    private String channelName;

    @Value("${queuename}")
    private String queueName;
    /**
     * redis消息监听器容器
     * @param connectionFactory
     * @param priceListenerAdapter  价格趋势和市场消息订阅处理器
     * @return
     */
    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
                                            MessageListenerAdapter priceListenerAdapter) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        //监听价格趋势和市场情况主题并绑定消息订阅处理器
        container.addMessageListener(priceListenerAdapter, new PatternTopic(channelName));

        return container;
    }

    /**
     * 价格趋势和市场消息订阅处理器,并指定处理方法
     * @param receiver
     * @return
     */
    @Bean
    MessageListenerAdapter priceListenerAdapter(MessageService receiver) {
        MessageListenerAdapter messageListenerAdapter = new MessageListenerAdapter(receiver, "priceReceive");
       // Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = this.jacksonSerializer();
       // messageListenerAdapter.setSerializer(jackson2JsonRedisSerializer);
        return messageListenerAdapter;
    }


    @Bean
    CountDownLatch latch() {
        return new CountDownLatch(1);
    }

    @Bean
    RedisTemplate template(RedisTemplate redisTemplate) {
        return redisTemplate;
    }

    private Jackson2JsonRedisSerializer jacksonSerializer(){
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        return jackson2JsonRedisSerializer;
    }
}